<template>
  <div class="presentManager">
    <x-header class="header" :left-options="{showBack: showHeaderBack,preventGoBack:true}" @on-click-back="goToPage('/')" ref="header">
      当前可赠送列表<a slot="right" @click="goToPage('/presentedList')" >赠送查询</a>
    </x-header>
    <div class="topHolder"></div>
    <box gap="1rem 0.8rem">
      <div class="filterArea" ref="filterArea">
        <div class="filterItem">台位：<x-button @click.native="showTablesByType = true" type="default" v-html="tablesByTypeText" :show-loading="loadingStatus" :disabled="loadingStatus" class="inlineBtn popPickerBtn"></x-button></div>
      </div>
      <popup-picker @on-change="changeTablesByTypeText();refreshList()" :show.sync="showTablesByType" :show-cell="false" :data="tablesByType" :columns="3" v-model="choosenTablesByType" ref="tablesByType" class="btn_popup-picker"></popup-picker>
      <br/>
      <scroller :height="scrollerHeight" lock-x use-pulldown use-pullup :pulldown-config="pulldownDefaultConfig" @on-pulldown-loading="refreshList()" :pullup-config="pullupDefaultConfig" @on-pullup-loading="loadMoreList" ref="loadMoreScroller">
        <div class="availableList">
          <div class="item" v-for="(item,index) in availableList" :key="index" @click="doAction(item)">
            <h5 class="name">客户：<span v-html="item.CUSTOMER_NAME"></span></h5>
            <span class="saled">已消费：¥ <span v-html="formatCurrency(item.payed)"></span>元</span>
            <span class="presented">已赠送：¥ <span v-html="formatCurrency(item.presented)"></span>元</span>
            <span class="dateTime">开单时间：<span v-html="item.ORDER_DATETIME"></span></span>
            <span class="table">房台：
              <span v-html="item.AREA"></span> - <span v-html="item.NUMBER"></span>（<span v-html="item.ROOM_PLATFORM_TYPE"></span>）
            </span>
            <div class="state">
              <span v-if="item.IS_BEAUTY == 1">美女台</span>
            </div>
          </div>
          <div class="listNoItem" v-if="availableList.length <= 0">暂无可赠送订单</div>
        </div>
      </scroller>
      <actionsheet v-model="showActionsheet" :menus="actionsheetMenu" @on-click-menu="actionsheetClick" @on-after-hide="initActionsheet" show-cancel></actionsheet>
    </box>
  </div>
</template>

<script>
  import {XButton, PopupPicker, Scroller, Box, Actionsheet, numberComma } from 'vux'
  import {getOrderIdList,getOrderByIds,getTablesByType} from "../../api";
  import {message,toDecimal2} from "../../common/util";

  export default {
    name:'presentManager',
    data(){
      return{
        showHeaderBack:this.GLOBAL.showHeaderBack,
        loadingStatus:true,
        tablesByTypeText:'',
        showTablesByType:false,
        choosenTablesByType:['allRegion','allRegion_of_allRoomType','allRoom_in_allRegion_of_allRoomType'],
        availableList:[],
        idArrayList:[],
        scrollerHeight:'',
        pulldownDefaultConfig:{
          content: '下拉刷新',
          height: 40,
          autoRefresh: false,
          downContent: '下拉刷新',
          upContent: '释放后刷新',
          loadingContent: '正在刷新...',
          clsPrefix: 'xs-plugin-pulldown-'
        },
        pullupDefaultConfig:{
          content: '上拉加载更多',
          pullUpHeight: 60,
          height: 40,
          autoRefresh: false,
          downContent: '释放后加载',
          upContent: '上拉加载更多',
          loadingContent: '加载中...',
          clsPrefix: 'xs-plugin-pullup-'
        },
        currentPage:0,
        totalItems:0,
        pageSize:10,
        onFetching:true,
        showActionsheet:false,
        actionsheetMenu:[
          {label: '订单详情',type: 'Default',value: 'orderDetail'},
          {label: '存酒库存签送',type: 'Default',value: 'keepPresent'},
          {label: '售卖库存签送',type: 'Default',value: 'salePresent'}
        ],
        clickedItem:{}
      }
    },
    components:{
      XButton,
      PopupPicker,
      Scroller,
      Box,
      Actionsheet
    },
    computed:{
      tablesByType:{
        get(){
          return this.$store.getters.getTablesOfAll
        },
        set(value){
          this.$store.commit('updateTablesOfAll',value)
        }
      }
    },
    methods:{
      goToPage(url){
        this.$router.push({path:url})
      },
      formatCurrency(number){
        return numberComma(toDecimal2(number))
      },
      refreshList(params){
        this.loadingStatus = true
        this.availableList = []
        this.currentPage = 0
        let reqParams = {
          choosenTablesByType:this.choosenTablesByType
        }
        getOrderIdList(reqParams).then((res)=>{
          if(res.status == 'success'){
            this.$nextTick(() => {
              if(this.$refs.loadMoreScroller) {
                this.$refs.loadMoreScroller.reset({top: 0})
                this.$refs.loadMoreScroller.donePulldown()
              }
              this.idArrayList = res.data
              this.totalItems = res.data.length
              this.loadMoreList({callback:(params && params.callback)?params.callback:null})
            })
          }else if(res.status == 'error') {
            message({message:res.msg,type:'error'})
            console.log('getOrderIdList error info:', res.msg)
          }
        }).catch((err)=>{console.log('getOrderIdList catch info:',err)})
      },
      loadMoreList(params){
        if (this.onFetching) {
          this.onFetching = false
          setTimeout(() => {
            let reqParams = [],start = this.currentPage*this.pageSize,end = start + this.pageSize - 1
            for(var i = start; i <= end; i++){
              if(this.idArrayList[i] != undefined)reqParams.push(this.idArrayList[i])
            }
            getOrderByIds(reqParams).then((res)=>{
              if(res.status == 'success'){
                if(res.data.length > 0){//后端实际用这个
                  //if (this.availableList.length < this.totalItems) {//前端测试用这个
                  for(var i = 0; i < res.data.length; i++){
                    this.availableList.push(res.data[i])
                  }
                  this.currentPage++
                }else{
                  message({message:'已经加载到底了！',type:'info'})
                }
                this.onFetching = true
                this.$nextTick(() => {
                  if(this.$refs.loadMoreScroller != undefined){
                    this.$refs.loadMoreScroller.donePullup()
                    this.$refs.loadMoreScroller.reset()
                  }
                })
              }else if(res.status == 'error') {
                message({message:res.msg,type:'error'})
                console.log('getOrderByIds error info:', res.msg)
              }
              this.setSize()
              this.loadingStatus = false
              if(params && params.callback && typeof params.callback == 'function')params.callback()
            }).catch((err)=>{console.log('getOrderByIds catch info:',err)})
          }, 500)
        }
      },
      setSize(){
        let outHeight = 0
        if(this.$refs.header)
          outHeight = this.$refs.header.$el.offsetHeight + this.$refs.filterArea.offsetHeight
        let contentHeight = window.screen.height - outHeight - 150
        this.scrollerHeight = contentHeight + 'px'
      },
      doAction(item){
        this.clickedItem = item
        if(item.IS_BEAUTY == 1) this.actionsheetMenu.push({label: '美女台签送',type: 'Default',value: 'girlPresent'})
        this.showActionsheet = true
      },
      initActionsheet(){
        this.actionsheetMenu = [
          {label: '订单详情',type: 'Default',value: 'orderDetail'},
          {label: '存酒库存签送',type: 'Default',value: 'keepPresent'},
          {label: '售卖库存签送',type: 'Default',value: 'salePresent'}
        ]
      },
      actionsheetClick (key, item) {
        //console.log(key, item)
        //if(this.clickedItem.payed > 0){
          if(key == 'salePresent'){
            this.$router.push({name:'选择要赠送商品',params:{type:'salePresent',orderId:this.clickedItem.ORDER_ID}})
          }else if(key == 'keepPresent'){
            this.$router.push({name:'选择要赠送商品',params:{type:'keepPresent',orderId:this.clickedItem.ORDER_ID}})
          }else if(key == 'girlPresent'){
            this.$router.push({name:'选择要赠送商品',params:{type:'girlPresent',orderId:this.clickedItem.ORDER_ID}})
          }else if(key == 'orderDetail'){
            this.$router.push({name:'订单详情',params:{orderId:this.clickedItem.ORDER_ID}})
          }else if(key == 'expiredWinePresent'){

          }
        //}else{
        //  message({message:'未消费的订单无法赠送',type:'error'})
        //}
      },
      changeTablesByTypeText(){
        this.tablesByTypeText = this.$refs.tablesByType&&this.$refs.tablesByType.getNameValues().replace(/ /g,' - ')+'<i class=\'iconfont icon-xiangxia2\'></i>'
      }
    },
    mounted(){
      this.initActionsheet()
      return new Promise((resolve,reject)=>{
        if(this.tablesByType.length <= 0)
          getTablesByType('global').then((res)=>{
            if(res.status == 'success'){
              this.tablesByType = res.data
              //this.$store.commit('updateTablesOfAll', res.data)
            }else if(res.status == 'error') {
              message({message:res.msg,type:'error'})
              console.log('getTablesByType error info:', res.msg)
            }
            resolve()
          }).catch((err)=>{console.log('getTablesByType catch info:',err)})
        else resolve()
      }).then(()=>{
        switch ('global') {
          case 'local':
            this.choosenTablesByType = [this.tablesByType[0].value,this.tablesByType[0].value + '_of_allroomType','allRoom_in_' + this.tablesByType[0].value + '_of_allroomType']
            break
          default:
            this.choosenTablesByType = ['allRegion','allRegion_of_allRoomType','allRoom_in_allRegion_of_allRoomType']
        }
        setTimeout(()=>{this.changeTablesByTypeText()},200)
        this.refreshList({callback:()=>{
            window.onresize = ()=>{
              this.setSize()
            }
          }})
        this.$store.commit('updateLoadingStatus',{isLoading:false})
      })
    },
    beforeDestroy(){
      window.onresize = ()=>{}
    }
  }
</script>

<style lang="scss" scoped>
  .presentManager{
    .filterArea{
      display: flex;justify-content: space-between;
    }
    .availableList{
      display: flex;flex-wrap:wrap;justify-content:space-between;
      .item{
        position: relative;overflow:hidden;min-height:5rem;width: 44%;margin:0 0 1rem;padding:0.8rem 2%;border-radius: 0.3rem;font-size:0.7rem;
        background-color: #e9e9e9;
        background-image: -webkit-linear-gradient(top,#ffffff,#e9e9e9);
        background-image: -moz-linear-gradient(top,#ffffff,#e9e9e9);
        background-image: -ms-linear-gradient(top,#ffffff,#e9e9e9);
        background-image: -o-linear-gradient(top,#ffffff,#e9e9e9);
        background-image: linear-gradient(top,#ffffff,#e9e9e9);
        -webkit-box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.2);
        box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.2);
        .name{font-size:0.8rem;max-width: 60%;margin-bottom:0.3rem;overflow: hidden;display: -webkit-box;-webkit-line-clamp: 2;-webkit-box-orient: vertical;}
        .saled{margin-bottom:0.3rem;overflow: hidden;display: -webkit-box;-webkit-line-clamp: 1;-webkit-box-orient: vertical;}
        .presented{margin-bottom:0.3rem;overflow: hidden;display: -webkit-box;-webkit-line-clamp: 1;-webkit-box-orient: vertical;}
        .dateTime{margin-bottom:0.3rem;overflow: hidden;display: -webkit-box;-webkit-line-clamp: 2;-webkit-box-orient: vertical;}
        .table{overflow: hidden;display: -webkit-box;-webkit-line-clamp: 2;-webkit-box-orient: vertical;}
        .state{position:absolute;right:0.4rem;top:0.6rem;
          span{color: #fff;padding:0.15rem 0.4rem;border-radius: 0.3rem;background: #bd2a78;}
        }
      }
    }
  }
</style>
